//课程表
class Solution {
public:
    bool canFinish(int n, vector<vector<int>>& prerequisites) {
        unordered_map<int, vector<int>> edges;
        vector<int> in(n);

        for (auto& nums : prerequisites) {
            int a = nums[0];
            int b = nums[1];
            // b->a
            edges[b].push_back(a);
            in[a]++;
        }

        queue<int> q;
        for (int i = 0; i < n; i++) {
            if (in[i] == 0)
                q.push(i);
        }
        while (q.size()) {
            int t = q.front();
            q.pop();
            for (auto a : edges[t]) {
                in[a]--;
                if (in[a] == 0)
                    q.push(a);
            }
        }
        for (auto& num : in)
            if (num)
                return false;
        return true;
    }
};

//课程表 II
class Solution {
public:
    vector<int> findOrder(int n, vector<vector<int>>& prerequisites) {
        unordered_map<int, vector<int>> edges;
        vector<int> in(n);
        vector<int> ret;
        for (auto& nums : prerequisites) {
            int a = nums[0];
            int b = nums[1];
            // b->a
            edges[b].push_back(a);
            in[a]++;
        }

        queue<int> q;
        for (int i = 0; i < n; i++) {
            if (in[i] == 0)
                q.push(i);
        }
        while (q.size()) {
            int t = q.front();
            ret.push_back(t);
            q.pop();
            for (auto a : edges[t]) {
                in[a]--;
                if (in[a] == 0)
                    q.push(a);
            }
        }
        for (auto& num : in)
            if (num)
                return {};
        return ret;
    }
};